const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");
router.post('/common/del', async ctx => {
    let ids = ctx.request.body.ids;
    let mod = ctx.request.body.mod;
    if(!mod) return ctx.err('未找到删除模型')
    if(!ids) return ctx.err('请选择要删除的数据')
    let soft = ctx.request.body.soft;
    let isTree = ctx.request.body?.isTree;
    let attrs = db.models[mod].getAttributes()
    if (isTree) {
        // 找出code 摸查子分类 并删除
        for(let id in ids) {
            let codeModel = await db.models[mod].findOne({
                where: {
                    id: ids[id]
                }
            })
            if(codeModel) {
                await db.models[mod].destroy({
                    where: {
                        code: {
                            [Op.like]: codeModel.code +'%'
                        }
                    }
                })
            }
        }
        ctx.suc('已删除 ' + ids.length + ' 条记录')
    }
    else {
        let where = {
            id: {
                [Op.in]: ids
            },
        }
        for(let i in attrs) {
            if (i === 'tenantId') {
                where.tenantId = ctx.user.tenantId
            }
        }
        if(soft) {
            let updata = {}
            for(let i in attrs) {
                if(i === 'dt') updata.dt = tools.getTime()
                if(i === 'dtime') updata.dtime = tools.getTime()
                if(i === 'dby') updata.dby = ctx.user.id
                if(i === 'isDel') updata.isDel = 1
            }
            if(!tools.xeisEmpty(updata)) {
                await db.transaction(async () => {
                    await db.models[mod].update(updata,
                        { where: where },
                    )
                },)
            }
        }
        else {
            await db.transaction(async () => {
                await db.models[mod].destroy({
                    where: where
                },)
            })
        }
        ctx.suc('已删除 ' + ids.length + ' 条记录')
    }
})

module.exports = router;